<template>
    <div>
        <basic-container>
            <div class="app-container">
                <el-form :model="otherQuery" ref="queryForm" size="small" :inline="true">

                    <el-form-item label="物料批次">
                        <el-input style="width: 240px;" v-model="otherQuery.batch" placeholder="请输入物料批次" clearable />
                    </el-form-item>
                    <el-form-item label="设备名称">
                        <el-select style="width: 180px;" v-model="otherQuery.facility_id" placeholder="请选择" clearable>
                            <el-option v-for="item in menuList" :key="item.facility_id" :label="item.name"
                                :value="item.facility_id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="物料编码">
                        <el-input style="width: 240px;" v-model="otherQuery.serial" placeholder="请输入物料编码" clearable />
                    </el-form-item>

                    <el-form-item label="日期查询">
                        <el-date-picker style="width: 250px;" v-model="value" clearable type="daterange"
                            value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期"
                            end-placeholder="结束日期">
                        </el-date-picker>
                        <el-button style="margin-left: 20px;" type="primary" icon="el-icon-search" size="mini"
                            @click="handleQuery">搜索</el-button>
                    </el-form-item>


                </el-form>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-download" size="mini"
                            @click="handleExport">导出</el-button>
                    </el-col>

                </el-row>
                <template>
                    <el-table :data="tableData" v-loading="loading" element-loading-text="拼命加载中"
                        element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)"
                        ref="table" style="width: 100%" border>
                        <el-table-column prop="batch" label="物料批次" width="180">
                        </el-table-column>
                        <el-table-column prop="facility_name" label="设备名称" align="center" width="180">
                            <template slot-scope="scope">
                                <div>{{ scope.row.facility_name }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="facility_serial" label="设备编码" align="center" width="180">
                            <template slot-scope="scope">
                                <div>{{ scope.row.facility_serial }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="serial" label="物料编号" align="center" width="130">
                        </el-table-column>

                        <el-table-column prop="status" label="是否合格" align="center" width="130">
                            <template slot-scope="scope">
                                <div>{{ scope.row.status ? "合格" : "不合格" }}</div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="time" label="时间" align="center" width="180">
                        </el-table-column>


                        <el-table-column v-for="col in dynamicColumns" :key="col.prop" :label="col.label"
                            :width="col.width">
                            <template #default="scope">
                                <div v-if="scope.row.db_message_resp">
                                    <div v-for="(item, index) in displayItems(scope.row.db_message_resp)" :key="index">
                                        {{ item[col.prop] }}
                                    </div>
                                    <div v-if="scope.row.db_message_resp.length > 2" class="expand-button"
                                        @click="toggleExpand(scope.row)">
                                        {{ scope.row.db_message_resp.isExpanded ? '收起' : '展开' }}
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <el-button size="mini" type="text" icon="el-icon-edit"
                                    @click="handleUpdate(scope.row)">编辑</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>

            </div>
            <pagination v-show="toNum > 0" :total="toNum" :page.sync="otherQuery.index" :limit.sync="otherQuery.size"
                @pagination="gitMeassList" />
        </basic-container>
        <el-dialog title="cpk计算" :visible.sync="CpkdialogVisible" width="80%">
            <div style="display: flex;">
                <div v-for="(item, index) in Cpklist" :key="index">
                    <div style="margin:0 20px;text-align: center;">
                        <div style="margin: 5px 0;">{{ item.key }}</div>
                        <div>{{ item.value }}</div>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="CpkdialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>


        <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <!-- <el-form-item label="物料批次" prop="batch">
                    <el-input v-model="form.batch" placeholder="请输入物料批次" />
                </el-form-item>
                <el-form-item label="设备名称" prop="facility_name">
                    <el-input v-model="form.facility_name" placeholder="请输入设备名称" />
                </el-form-item>
                <el-form-item label="设备编码" prop="facility_serial">
                    <el-input v-model="form.facility_serial" placeholder="请输入设备编码" />
                </el-form-item>
                <el-form-item label="物料编号" prop="serial">
                    <el-input v-model="form.serial" placeholder="请输入物料编号" />
                </el-form-item> -->
                <el-form-item label="是否合格" prop="status">
                    <el-select v-model="form.status" placeholder="请选择">
                        <el-option label="合格" :value="true"></el-option>
                        <el-option label="不合格" :value="false"></el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="时间" prop="time">
                    <el-input v-model="form.time" placeholder="请输入时间" />
                </el-form-item> -->

                <template v-if="form.db_message_resp && form.db_message_resp.length > 0">
                    <div v-for="(item, index) in form.db_message_resp" :key="index" class="dynamic-form-row">
                        <el-form-item :label="getColumnLabel('key')" :prop="'db_message_resp.' + index + '.key'" class="dynamic-form-item">
                            <el-input v-model="item.key" placeholder="请输入测试项名称" />
                        </el-form-item>
                        <el-form-item :label="getColumnLabel('floor')" :prop="'db_message_resp.' + index + '.floor'" class="dynamic-form-item">
                            <el-input v-model="item.floor" placeholder="请输入测试项下限" />
                        </el-form-item>
                        <el-form-item :label="getColumnLabel('value')" :prop="'db_message_resp.' + index + '.value'" class="dynamic-form-item">
                            <el-input v-model="item.value" placeholder="请输入测试项值" />
                        </el-form-item>
                        <el-form-item :label="getColumnLabel('upper')" :prop="'db_message_resp.' + index + '.upper'" class="dynamic-form-item">
                            <el-input v-model="item.upper" placeholder="请输入测试项上限" />
                        </el-form-item>
                    </div>
                </template>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    getkindList,
    getdetails,
    getdkind,
    getdTaskkind,
    getCpk,
    Eitputdata
} from "@/api/component";

export default {
    data() {
        return {
            tableTile: ['机种名称', '产品编码'],
            CpkdialogVisible: false,
            Cpklist: [],
            checked: false,
            roleOptions: [],
            cpkNumbe: 1,
            NubIndex: null,
            produInd: null,
            tabPosition: "left",
            tableData: [],
            propObj: {
                multiple: true,
                value: "mark",
                label: "label",
                children: "children",
            },
            loading: false,
            towLad: false,
            showSearch: true,
            value1: [],
            total: 1,
            inMess: [],
            menuList: [],
            options: [
                {
                    value: "1",
                    label: "生效中",
                },
                {
                    value: "2",
                    label: "禁用",
                },
                {
                    value: "3",
                    label: "审核中",
                },
            ],
            // 弹出层标题
            title: "",
            open: false,
            toNum: 0,
            isExpandAll: false,
            restaurants: [],
            activeName: null,
            refreshTable: true,
            otherQuery: {
                facility_id: null,
                batch: null,
                serial: null,
                start: null,
                finish: null,
                index: 1,
                size: 10,
            },
            queryParams: {
                index: 1,
                size: 1000,
            },
            value: null,
            form: {},
            rules: {},
            max16: '',
            max17a: '',
            max19: '',
            max22: '',
            max23: '',
            max24: '',
            max5: '',
            max8: '',
            titleMax16: '最大16',
            titleMax17a: '最大17a',
            titleMax19: '最大19',
            titleMax22: '最大22',
            titleMax23: '最大23',
            titleMax24: '最大24',
            titleMax5: '最大5',
            titleMax8: '最大8',
        };
    },
    created() {

    },

    computed: {
        dynamicColumns() {
            if (this.tableData.length > 0 && this.tableData[0].db_message_resp) {
                const firstItem = this.tableData[0].db_message_resp[0];
                const columnOrder = ['key', 'floor', 'value', 'upper'];

                return columnOrder
                    .filter(key => Object.keys(firstItem).includes(key))
                    .map(key => ({
                        prop: key,
                        label: this.getColumnLabel(key),
                        width: key === "key" ? 200 : 100
                    }));
            }
            return [];
        }
    },

    mounted() {
        function formatDate(date) {
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            return `${year}-${month}-${day}`;
        }
        // 获取今天的日期
        const today = new Date();
        // 获取前三个月的日期
        const threeMonthsAgo = new Date(today);
        threeMonthsAgo.setMonth(today.getMonth() - 3);
        // 格式化日期为 "yyyy-MM-dd"
        const formattedToday = formatDate(today);
        const formattedThreeMonthsAgo = formatDate(threeMonthsAgo);
        this.queryParams.start = formattedThreeMonthsAgo
        this.queryParams.finish = formattedToday
        this.value = [formattedThreeMonthsAgo, formattedToday]
        this.getList()
        this.getdkindList();

    },
 
    methods: {
        getList() {
            getkindList(this.queryParams).then((response) => {
                this.menuList = response.data.data;
                console.log(this.menuList, "99999999999");
                this.firstQuery()
            });
        },
        cancel() {
            this.open = false;
            this.reset();
        },
        handleUpdate(row) {
            this.open = true;
            this.title = "编辑";
            this.form = JSON.parse(JSON.stringify(row));
        },
        handleCpk() {
            let allFalse = this.tableData.every(item => item.db_message_resp.every(obj => obj.isBoole === false));
            if (allFalse) {
                return this.$message.error('请先选择要计算的数据');
            } else {
                let newdata = [];
                let processedKeys = {};
                this.tableData.forEach(item => {
                    item.db_message_resp.forEach(entry => {
                        if (entry.isBoole && !processedKeys[entry.key]) {

                            processedKeys[entry.key] = true;
                            newdata.push({ key: entry.key, values: [entry.value] });
                        } else if (entry.isBoole) {

                            let existingEntry = newdata.find(el => el.key === entry.key);
                            existingEntry.values.push(entry.value);
                        }
                    });
                });

                let newArr = {
                    'data': newdata
                }
                getCpk(newArr).then((res => {
                    this.Cpklist = res.data.data
                    this.CpkdialogVisible = true
                })
                )
            }
        },

        handleExport() {
            this.$confirm('是否将数据导出为EXcel文档？').then(() => {
                const params = new URLSearchParams();
                this.value == null ? '' : params.append('start', this.value[0]);
                this.value == null ? '' : params.append('finish', this.value[1]);
                this.otherQuery.sequence == null ? '' : params.append('sequence', this.otherQuery.sequence);
                this.otherQuery.aircraft_id == null ? '' : params.append('aircraft_id', this.otherQuery.aircraft_id);
                this.otherQuery.facility_id == null ? '' : params.append('facility_id', this.otherQuery.facility_id);
                this.otherQuery.task_id == null ? '' : params.append('task_id', this.otherQuery.task_id);
                const url = new URL('http://10.1.109.252:8080/api/query/component/output');
                url.search = params.toString();
                window.location.href = url.toString();

            })
        },
        firstQuery() {
            (this.otherQuery = {
                facility_id: null,
                batch: null,
                serial: null,
                start: null,
                finish: null,
                index: 1,
                size: 10,
            }),
                this.otherQuery.start = this.value == null ? null : this.value.length > 0 ? this.value[0] : null
            this.otherQuery.finish = this.value == null ? null : this.value.length > 0 ? this.value[1] : null
            this.gitMeassList();
        },
        gitMeassList() {
            this.otherQuery.start = this.value == null ? null : this.value.length > 0 ? this.value[0] : null
            this.otherQuery.finish = this.value == null ? null : this.value.length > 0 ? this.value[1] : null
            this.loading = true;
            this.tableData = []
            getdetails(this.otherQuery).then((res) => {
                this.tableData = res.data.data;
                console.log(this.tableData, 'ppppp');
                if (this.tableData.length == 0) {
                    this.tableData = []
                    this.loading = false;
                } else {
                    this.tableData.forEach(item => {
                        item.db_message_resp.forEach(obj => {
                            this.$set(obj, 'isBoole', false)
                        });
                    });
                    console.log(this.tableData);
                    this.toNum = res.data.total;
                    this.loading = false;
                }

            });
        },
        handleQuery() {
            this.value = this.value == null ? [] : this.value;
            let queryData = {
                start: this.value.length > 0 ? this.value[0] : null,
                finish: this.value.length > 0 ? this.value[1] : null,
                facility_id: this.otherQuery.facility_id ? this.otherQuery.facility_id : null,
                batch: this.otherQuery.batch ? this.otherQuery.batch : null,
                serial: this.otherQuery.serial ? this.otherQuery.serial : null,

            };
            getdetails(queryData).then((res) => {
                this.tableData = res.data.data;
                if (this.tableData.length == 0) {
                    this.tableData = []
                    this.loading = false;
                } else {
                    this.tableData.forEach(item => {
                        this.$set(item.db_message_resp, 'isExpanded', false);
                        item.db_message_resp.forEach(obj => {
                            this.$set(obj, 'isBoole', false)
                        });
                    });
                    const firstData = this.tableData[0];
                    const keysOfFirstData = [];
                    firstData.db_message_resp.forEach((item) => {
                        keysOfFirstData.push(item.key);
                    });
                }

                this.toNum = res.data.total;
            });
            this.loading = false;
        },

        getdkindList() {
            getdkind().then((res) => {
                this.roleOptions = res.data.data;
                console.log(this.roleOptions, '99999');
            });
        },
        querySearchAsync(queryString) {
            if (queryString == null) return;

            let quey = {
                name: queryString,
            };
            getdTaskkind(quey).then((res) => {
                this.restaurants = res.data.data;
            });
        },
        getColumnLabel(key) {
            const labelMap = {
                'floor': '测试项下限',
                'key': '测试项名称',
                'value': '测试项值',
                'upper': '测试项上限'
            };
            return labelMap[key] || key;
        },
        displayItems(items) {
            if (!items) return [];
            if (items.length <= 2) return items;
            return items.slice(0, items.isExpanded ? items.length : 2);
        },
        toggleExpand(row) {
            if (!row.db_message_resp.isExpanded) {
                this.$set(row.db_message_resp, 'isExpanded', true);
            } else {
                this.$set(row.db_message_resp, 'isExpanded', false);
            }
        },

        
        submitForm() {
            console.log(this.form);
            // 构造提交的数据格式
            const submitData = {
                ...this.form,
                data: this.form.db_message_resp  // 将 db_message_resp 改为 data
            };
            delete submitData.db_message_resp;  // 删除原来的 db_message_resp

            // 调用 Eitputdata 接口
            Eitputdata(submitData).then(res => {
                console.log(res);
                
                this.$message.success("修改成功");
                this.open = false;
                // 刷新表格数据
                this.gitMeassList();
            }).catch(error => {
                this.$message.error(error,"修改失败");
            });
        },
        reset() {
            this.form = {
                batch: '',
                facility_name: '',
                facility_serial: '',
                serial: '',
                status: true,
                time: '',
                db_message_resp: []
            };
            if (this.$refs["form"]) {
                this.$refs["form"].resetFields();
            }
        },
    },
};
</script>

<style lang="scss" scoped>
.message {
    width: 198%;
    background: #f8f8f9;
    display: flex;
    overflow-x: scroll;
}

.activeClass {
    color: red;
}

::v-deep .el-table .el-table__body-wrapper::-webkit-scrollbar {
    height: 15px !important;
    /* 设置水平滚动条的高度 */
}

.expand-button {
    color: #409EFF;
    cursor: pointer;
    font-size: 13px;
    margin-top: 5px;

    &:hover {
        text-decoration: underline;
    }
}

.dialog-footer {
    text-align: right;
}

.dynamic-form-row {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 10px;
    border-bottom: 1px dashed #eee;
    padding-bottom: 10px;

    &:last-child {
        border-bottom: none;
    }
}

.dynamic-form-item {
    flex: 1;
    min-width: 200px;
    margin-right: 10px;
    margin-bottom: 0;

    :deep(.el-form-item__label) {
        width: 100px !important;
    }

    :deep(.el-form-item__content) {
        margin-left: 100px !important;
    }
}
</style>